package com.zcx.mall.oauth.controller;

import com.zcx.mall.common.web.api.ApiResult;
import com.zcx.mall.common.web.exception.BizExcepton;
import com.zcx.mall.oauth.constant.OauthBizConstant;
import com.zcx.mall.oauth.entity.UserInfoEntity;
import com.zcx.mall.oauth.service.SmsService;
import com.zcx.mall.oauth.service.UserInfoService;
import com.zcx.mall.oauth.vo.SmsResult;
import com.zcx.mall.oauth.vo.ValidateSmsRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SmsController {

    @Autowired
    SmsService smsService;

    @Autowired
    UserInfoService userInfoService;

    /**
     * 手机号验证码
     * @return
     */
    @PostMapping("/sendSms")
    public @ResponseBody
    ApiResult registerSms(String moblieNo, String type) {
        SmsResult smsResult = smsService.sendSms(moblieNo, OauthBizConstant.SmsType.getSmsType(type));
        return new ApiResult(smsResult);
    }

    /**
     * 手机号验证码
     * @return
     */
    @PostMapping("/registerSms")
    public @ResponseBody
    ApiResult validateSms(@RequestBody @Validated ValidateSmsRequest validateSmsRequest) {
        //校验验证码
        smsService.validateSms(validateSmsRequest);

        //是否注册用户
        if (OauthBizConstant.SmsType.REGISTER.getValue().equals(validateSmsRequest.getType())) {
            UserInfoEntity userInfoEntity = userInfoService.selectByMobile(validateSmsRequest.getMobile());
            if (userInfoEntity != null) {
                throw new BizExcepton("注册手机号已被注册");
            }
        }
        //成功
        return new ApiResult();
    }
}
